import cv2
import numpy as np
import pyautogui
import time
import os
import threading
import yaml
import time

class SmartGrillMonitor:
    def __init__(self, display_scale=1.0):
        """
        实时监控指定区域的画面变化
        :param display_scale: 显示缩放比例
        """
        pyautogui.PAUSE = 0.05  # 减少点击延迟

        #读取yaml文件
        with open('config.yaml', 'r') as file:
            config = yaml.safe_load(file)

        # 定义监控区域 (x1, y1, x2, y2)
        self.monitor_roi = tuple(config['monitor']['roi'])
        self.display_scale = display_scale
        
        # 创建调试窗口
        self.window_name = "game"
        cv2.namedWindow(self.window_name, cv2.WINDOW_NORMAL)
        self._resize_window()
        self._move_window_to_bottom_right()

        # 模板中文名映射
        self.template_names = {
            "temCus1.png": "芦笋牛肉",
            "temCus2.png": "番茄牛肉",
            "temCus3.png": "纯牛肉",
            "temCus4.png": "红酒",
            "temCus7.png": "1",
            "temCus8.png": "2",
            "temCus9.png": "3",
            "temCus10.png": "4",
            "temCus11.png": "5",
            
            # 添加更多模板文件及其对应的中文名
        }

        self.template_names2 = {
            "temDishs1.png": "芦笋牛肉",
            "temDishs2.png": "番茄牛肉",
            "temDishs3.png": "纯牛肉",
            "temDishs4.png": "红酒",
            "temDishs7.png": "1",
            "temDishs8.png": "2",
            "temDishs9.png": "3",
            "temDishs10.png": "4",
            "temDishs11.png": "5",
        }

        # 初始化计时器
        self.last_print_time = time.time()

    def _resize_window(self):
        """调整窗口尺寸"""
        scaled_w = int((self.monitor_roi[2] - self.monitor_roi[0]) * self.display_scale)
        scaled_h = int((self.monitor_roi[3] - self.monitor_roi[1]) * self.display_scale)
        cv2.resizeWindow(self.window_name, scaled_w, scaled_h)

    def _move_window_to_bottom_right(self):
        """将窗口移动到屏幕右下角任务栏之上"""
        # 获取屏幕分辨率
        screen_width, screen_height = pyautogui.size()
        
        # 计算窗口右下角位置
        window_width = int((self.monitor_roi[2] - self.monitor_roi[0]) * self.display_scale)
        window_height = int((self.monitor_roi[3] - self.monitor_roi[1]) * self.display_scale)
        x = screen_width - window_width - 30  # 窗口左上角的 x 坐标
        y = screen_height - window_height - 100  # 窗口左上角的 y 坐标（减去 50 以贴近任务栏）
        
        # 移动窗口
        cv2.moveWindow(self.window_name, x, y)

    def _capture_region(self):
        """捕获指定区域的画面"""
        x1, y1, x2, y2 = self.monitor_roi
        screen = pyautogui.screenshot(region=(x1, y1, x2 - x1, y2 - y1))
        return cv2.cvtColor(np.array(screen), cv2.COLOR_RGB2BGR)

    def _match_templates(self, frame):
        """匹配当前目录下 temCus 文件夹中的 PNG 文件"""
        template_dir = "exam/game/temCus"
        if not os.path.exists(template_dir):
            print(f"目录 {template_dir} 不存在")
            return frame, {}

        detected_names = {}  # 用于存储检测到的中文名及其坐标

        for filename in os.listdir(template_dir):
            if filename.endswith(".png"):
                template_path = os.path.join(template_dir, filename)
                template = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE)
                if template is None:
                    print(f"无法加载模板文件: {template_path}")
                    continue

                # 模板匹配
                result = cv2.matchTemplate(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), template, cv2.TM_CCOEFF_NORMED)
                _, max_val, _, max_loc = cv2.minMaxLoc(result)

                # 如果匹配度大于 0.9，则画出绿框并记录中文名及坐标
                if max_val > 0.9:  
                    h, w = template.shape
                    top_left = max_loc
                    bottom_right = (top_left[0] + w, top_left[1] + h)
                    cv2.rectangle(frame, top_left, bottom_right, (0, 255, 0), 2)

                    # 获取模板中文名并记录
                    chinese_name = self.template_names.get(filename, "未知模板")
                    detected_names[chinese_name] = (top_left[0] + w // 2, top_left[1] + h // 2)  # 记录中心坐标

        # 每 3 秒打印一次检测到的内容，显示 3 秒后清屏
        current_time = time.time()
        if current_time - self.last_print_time >= 3:
            if detected_names:
                print("检测到客户匹配内容:")
                for name, coord in detected_names.items():
                    print(f"- {name} (坐标: {coord})")
            else:
                print("未检测到客户匹配内容")
            
            # 显示 3 秒后清屏
            time.sleep(0.5)
            print("\033[H\033[J")  # 清屏
            self.last_print_time = current_time

        return frame, detected_names
    
    def _match_dish_templates(self, frame):
        """匹配 temDishs 和 temDishsOnTop 文件夹中的 PNG 文件"""
        detected_names = {}  # 用于存储检测到的中文名及其坐标

        # 遍历 temDishs 文件夹
        template_dir = "exam/game/temDishs"
        if os.path.exists(template_dir):
            for filename in os.listdir(template_dir):
                if filename.endswith(".png"):
                    template_path = os.path.join(template_dir, filename)
                    template = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE)
                    if template is None:
                        continue

                    # 模板匹配
                    result = cv2.matchTemplate(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), template, cv2.TM_CCOEFF_NORMED)
                    _, max_val, _, max_loc = cv2.minMaxLoc(result)

                    # 如果匹配度大于 0.9，则记录中文名及坐标
                    if max_val > 0.9:
                        h, w = template.shape
                        top_left = max_loc
                        chinese_name = self.template_names2.get(filename, "未知模板")
                        detected_names[chinese_name] = (top_left[0] + w // 2, top_left[1] + h // 2)

        # 遍历 temDishsOnTop 文件夹
        template_dir = "exam/game/temDishsOnTop"
        if os.path.exists(template_dir):
            for filename in os.listdir(template_dir):
                if filename.endswith(".png"):
                    template_path = os.path.join(template_dir, filename)
                    template = cv2.imread(template_path, cv2.IMREAD_GRAYSCALE)
                    if template is None:
                        continue

                    # 模板匹配
                    result = cv2.matchTemplate(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), template, cv2.TM_CCOEFF_NORMED)
                    _, max_val, _, max_loc = cv2.minMaxLoc(result)

                    # 如果匹配度大于 0.9，则记录中文名及坐标
                    if max_val > 0.9:
                        h, w = template.shape
                        top_left = max_loc
                        chinese_name = self.template_names2.get(filename.replace("OnTop", ""), "未知模板")
                        detected_names[chinese_name] = (top_left[0] + w // 2, top_left[1] + h // 2)

        # 每 3 秒打印一次检测到的内容，显示 3 秒后清屏
        current_time = time.time()
        if current_time - self.last_print_time >= 3:
            if detected_names:
                print("检测到成菜匹配内容:")
                for name, coord in detected_names.items():
                    print(f"- {name} (坐标: {coord})")
            else:
                print("未检测到成菜匹配内容")
            
            # 显示 3 秒后清屏
            time.sleep(0.5)
            print("\033[H\033[J")  # 清屏
            self.last_print_time = current_time

        return frame, detected_names

    def _click_match(self, coord):
        current_time = time.time()
        if hasattr(self, 'last_click_time') and current_time - self.last_click_time < 0.5:
            return
        
        # 第一次点击
        pyautogui.click(coord[0] + self.monitor_roi[0], coord[1] + self.monitor_roi[1])
        # 增加短暂的延迟（1 秒）
        time.sleep(4)
        # 第二次点击
        pyautogui.click(coord[0] + self.monitor_roi[0], coord[1] + self.monitor_roi[1])
        # 增加点击间隔（0.8 秒）
        time.sleep(4)

    def run(self):
        try:
            while True:
                start_time = time.time()
                frame = self._capture_region()
                customer_frame, customer_matches = self._match_templates(frame.copy())
                dish_frame, dish_matches = self._match_dish_templates(frame.copy())

                # 检查并点击匹配项
                for name, coord in dish_matches.items():
                    if name in customer_matches:
                        print(f"检测到一致匹配: {name}, 点击坐标: {coord}")
                        threading.Thread(target=self._click_match, args=(coord,)).start()

                # 显示画面
                combined_frame = cv2.addWeighted(customer_frame, 0.5, dish_frame, 0.5, 0)
                scaled_frame = cv2.resize(combined_frame, 
                                         (int((self.monitor_roi[2] - self.monitor_roi[0]) * self.display_scale),
                                          int((self.monitor_roi[3] - self.monitor_roi[1]) * self.display_scale)))
                cv2.imshow(self.window_name, scaled_frame)

                # 控制循环频率
                elapsed = time.time() - start_time
                wait_ms = max(1, int((0.03 - elapsed) * 1000))
                if cv2.waitKey(wait_ms) == ord('q'):  # 检测是否按下了 'q' 键
                    break

        finally:
            cv2.destroyAllWindows()

if __name__ == "__main__":
    # 初始化监控器
    monitor = SmartGrillMonitor(display_scale=0.4)  # 缩放比例为 0.4
    monitor.run()